package com.zzw.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.zzw.util.UploadUtil;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private Button btn1;
    private Button btn2;
    private String filePath;

    // 服务器路径
    private String uploadUrl = "http://www.maizitime.com:8881/upload_test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn1.setOnClickListener(new ButtonClickListener());
        btn2.setOnClickListener(new ButtonClickListener());
    }

    class ButtonClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn1:
                    chooseFile();
                    break;
                case R.id.btn2:
                    new Thread() {
                        @Override
                        public void run() {
                            UploadUtil.uploadFile(new File(filePath), uploadUrl);
                            super.run();
                        }
                    }.start();
                    break;
                default:
                    break;
            }
        }
    }

    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    // 获得要上传文件的路径
                    Uri uri = data.getData();
                    filePath = uri.getPath();
                    Log.i("test", "filePath" + filePath);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

